<?php

namespace App\Http\Middleware;

use App\Admin\Arole;
use Closure;
use Illuminate\Support\Facades\Route;

class Rbac
{
    public function handle($request, Closure $next)
    {
        $admin = session()->get('admin');
        if(!$admin){
            return redirect('admin/login');
        }
        $admin = $admin[0]->id;
        //查询用户当前登录用户的权限
        $permissions = Arole::select('power.*')
            ->LeftJoin('rpower', 'rpower.role_id', 'arole.role_id')
            ->LeftJoin('power', 'power.id', 'rpower.rule_id')
            ->where('arole.user_id', $admin)
            ->groupBy('power.id')
            ->get();
//       dd( $permissions );
        $pers = array('Admin/index');
//        dump($current = Route::current()->uri());
//        dd($permissions);
        foreach ($permissions as $permission) {
            $pers[] = $permission->name;
        };
//        dd($pers);
        //dump($pers);
//        //得到数组的结构
        foreach ($permissions as $permission) {
            //取出来顶级的元素
            if ($permission->parent_id == 0) {
                foreach ($permissions as $v)
                    if ($permission->id == $v->parent_id) {
                        $tree[$permission->display_name][] = $v;
                    }
            }
        }
//        dd($tree);
        $current = Route::current()->uri();
//        var_dump($current);
//        var_dump($pers);
//         dd($current);
        if (!in_array($current, $pers)) {
        return back()->with('mess', '你没有权限访问');
    }
        return $next($request);
    }
}

